package com.woniuxy.shiro.Utils;

import com.woniuxy.entity.User;
import com.woniuxy.service.ManagerService;
import com.woniuxy.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description: TODO(用一句话描述这个类的作用)
 * @Author 18452
 * @Date 2021/5/6 19:19
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Resource
    private ManagerService managerService;

    @Autowired
    UserService userService;

    //设置名称
    @Override
    public void setName(String name) {
        super.setName("MyRealm");
    }

    //添加支持

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof MyJWT;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("MyRealm.doGetAuthenticationInfo, 用户认证方法进入!");
        String myJWT = (String) token.getCredentials();
        String username = JWTUtil.getUserName(myJWT);
        if (username==null){
            throw new AuthenticationException("token无效");
        }
        //通过用户名,查出当前用户密码
        User user = userService.selectUser(username);
        if (user==null){
            throw new AuthenticationException("User 不存在");
        }
        //通过存入的myJWT与传入的账号密码进行验证, 账号密码是否正确(类比之前手动比较密码~~~~)
        if (JWTUtil.verify(myJWT,username,user.getPassword())) {
            return new SimpleAuthenticationInfo(myJWT,myJWT,this.getName());
        }else {
            throw new AuthenticationException("用户名或者密码错误");
        }
    }
}
